package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.pojo.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import sun.security.provider.ConfigFile;
import util.IdWorker;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class SpitService {
    @Autowired
    private SpitDao spitDao;
    @Autowired
    IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;

    public List<Spit> findAll(){
        return spitDao.findAll();
    }
    public Spit findById(String id){
        return spitDao.findById(id).get();
    }
    public void save(Spit spit){
        spit.set_id(idWorker.nextId()+"");
        spit.setPublishtime(new Date());//发布日期
        spit.setShare(0);  //分享数
        spit.setThumbup(0);//点赞数
        spit.setState("1");//状态
        //spit.setUserid();
        spit.setVisits(0);//浏览量
        //如果当前添加的吐槽，有父节点，那么父节点的吐槽数需要+1
        if(!StringUtils.isEmpty(spit.getParentid())){
            Query query = new Query();
            Update update = new Update();
            query.addCriteria(Criteria.where("_id").is(spit.getParentid()));
            //不需要检测父节点的comment是否为空，monogo会自动吧null变成0
            update.inc("comment",1);//父节点的回复数+1
            mongoTemplate.updateFirst(query,update,"spit");
        }
        spit.setComment(0);//回复数

        spitDao.save(spit);
    }
    public void update(Spit spit){
        spitDao.save(spit);
    }
    public void deleteById(String id){
        spitDao.deleteById(id);
    }

    public Page<Spit> findByParentId(String parentid,int page,int size){
        Pageable pageable = PageRequest.of(page-1,size);
        return spitDao.findByParentid(parentid,pageable);
    }

    public void thumbup(String spitId) {
        //方式1：效率有问题，需要和数据库交互两次
//        Spit spit = spitDao.findById(spitId).get();
//        spit.setThumbup( spit.getThumbup() == null ? 1 : spit.getThumbup() + 1);
//        spitDao.save(spit);
        //方式2： 使用原生的mongo命令 db.spit.update({"_id":1},{$inc:{"thumbup":NumberInt(1)}})
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(spitId));
        Update update = new Update();
        update.inc("thumbup",1);

        mongoTemplate.updateFirst(query,update,"spit");

    }
}
